# -*- coding:utf-8 -*-
#返回一个结果
def calc_sum(*args):
    ax = 0
    for x in args:
        ax = ax + x
    return ax

print(calc_sum(1,2,3))

#返回一个函数
def lazy_sum(*args):
    def sum():
        ax = 0
        for n in args:
            ax +=n
        return ax
    return sum

f = lazy_sum(1,23,1)
#返回一个函数，调用后才会被执行
print(f())

#闭包
# 返回闭包时牢记一点：返回函数不要引用任何循环变量，或者后续会发生变化的变量。
def count():
    def f(j):
        def g():
            return j*j
        return g
    fs =[]
    for i in range(1,4):
        fs.append(f(i))
    return fs

f1,f2,f3=count()
print("-------------------")
print(f1())
print(f2())
print(f3())
print("-------------------")

#test
#利用闭包返回一个计数器函数，每次调用它返回递增整数：
def createCounter():
    i = [0]
    def counter():
        i[0] = i[0] + 1
        return i[0]
    return counter

# 测试:
counterA = createCounter()
print(counterA(), counterA(), counterA(), counterA(), counterA()) # 1 2 3 4 5
counterB = createCounter()
if [counterB(), counterB(), counterB(), counterB()] == [1, 2, 3, 4]:
    print('测试通过!')
else:
    print('测试失败!')